package patrol.mobile.com.mobilepatrol.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.OtherOfficeDetailBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.picker.matisse.Matisse;
import patrol.mobile.com.mobilepatrol.picker.matisse.MimeType;
import patrol.mobile.com.mobilepatrol.picker.matisse.engine.GlideEngine;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.DateUtil;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.MySpinner;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

import static patrol.mobile.com.mobilepatrol.activity.security.emergency.EmergencySaveCheck2Activity.REQUEST_CODE_VSELECT;
import static patrol.mobile.com.mobilepatrol.utils.DateUtil.format1;

public class MissionActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {


    @BindView(R.id.tv_title)
    EditText tvTitle;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_register_org)
    TextView tvRegisterOrg;
    @BindView(R.id.tv_register_time)
    TextView tvRegisterTime;
    @BindView(R.id.rb_org)
    RadioButton rbOrg;
    @BindView(R.id.rb_person)
    RadioButton rbPerson;
    @BindView(R.id.rg_type)
    RadioGroup rgType;
    @BindView(R.id.sp_org)
    MySpinner spOrg;
    @BindView(R.id.lin_org)
    LinearLayout linOrg;
    @BindView(R.id.sp_leader1)
    MySpinner spLeader1;
    @BindView(R.id.sp_leader2)
    MySpinner spLeader2;
    @BindView(R.id.sp_opter)
    MySpinner spOpter;
    @BindView(R.id.lin_person)
    LinearLayout linPerson;
    @BindView(R.id.rb_nor)
    RadioButton rbNor;
    @BindView(R.id.rb_hurrey)
    RadioButton rbHurrey;
    @BindView(R.id.rb_ergent)
    RadioButton rbErgent;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_content)
    EditText tvContent;
    @BindView(R.id.recyclerView_pic)
    RecyclerView recyclerViewPic;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    private String id;
    private OtherOfficeDetailBean data;
    private List<DeviceDetailImgBean> deviceDetailImgBeans;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<String> listleader1 = new ArrayList<>();
    private List<String> listleader2 = new ArrayList<>();
    private List<String> listrespone = new ArrayList<>();
    private List<String> listorg = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    private List<OtherOfficeDetailBean.UserScheduleListBean> userScheduleList;
    private String videoPath = "";
    private String urgent = "普通";
    private String exeUserIds = "";
    private String exeOrgIds = "";
    private String directorId = "";
    private String responsibleId = "";
    private String taskType = "0";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_mission_detail;
    }

    @Override
    public void initView() {
        super.initView();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CommonUtil.exitActivityAndBackAnim(MissionActivity.this, true);
                    }
                });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("任务登记");

    }

    @Override
    public void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(id)) {
            initImagePicker();
            selImageList = new ArrayList<>();
            adapter = new ImagePickerAdapter(this, selImageList, limitSize);
            adapter.setOnItemClickListener(this);
            recyclerViewPic.setLayoutManager(new GridLayoutManager(this, limitSize));
            recyclerViewPic.setHasFixedSize(true);
            recyclerViewPic.setAdapter(adapter);
            tvRegister.setText(UserManager.getUser().getUsername());
            tvRegisterOrg.setText(UserManager.getUser().getBmname());
            tvRegisterTime.setText(TimeUtils.dateString4(System.currentTimeMillis()));
            tvRegisterTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //时间选择器
                    TimePickerView pvTime = new TimePickerView.Builder(MissionActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            tvRegisterTime.setText(DateUtil.convert2String(date, format1));
                        }
                    }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                    pvTime.show();
                }
            });
            tvTime.setText(TimeUtils.dateString4(System.currentTimeMillis()));
            tvTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //时间选择器
                    TimePickerView pvTime = new TimePickerView.Builder(MissionActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            tvTime.setText(DateUtil.convert2String(date, format1));
                        }
                    }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                    pvTime.show();
                }
            });
            for (int i = 0; i < UserManager.getUsers().size(); i++) {
                listleader1.add(UserManager.getUsers().get(i).getRyname());
            }
            for (int i = 0; i < UserManager.getUsers().size(); i++) {
                listleader2.add(UserManager.getUsers().get(i).getRyname());
            }
            for (int i = 0; i < UserManager.getUsers().size(); i++) {
                listrespone.add(UserManager.getUsers().get(i).getRyname());
            }
            for (int i = 0; i < UserManager.getUsers().size(); i++) {
                listorg.add(UserManager.getUsers().get(i).getBmname());
            }
            exeOrgIds = UserManager.getUsers().get(0).getBmcode();
            exeUserIds = UserManager.getUsers().get(0).getRyid();
            directorId = UserManager.getUsers().get(0).getRyid();
            responsibleId = UserManager.getUsers().get(0).getRyid();
            spLeader1.setmDatas(listleader1, new MySpinner.CallBack() {
                @Override
                public void onSelect(int position) {
                    directorId = UserManager.getUsers().get(position).getRyid();
                }
            });
            spLeader2.setmDatas(listleader2, new MySpinner.CallBack() {
                @Override
                public void onSelect(int position) {
                    responsibleId = UserManager.getUsers().get(position).getRyid();
                }
            });
            spOpter.setmDatas(listrespone, new MySpinner.CallBack() {
                @Override
                public void onSelect(int position) {
                    exeUserIds = UserManager.getUsers().get(position).getRyid();
                }
            });
            spOrg.setmDatas(listorg, new MySpinner.CallBack() {
                @Override
                public void onSelect(int position) {
                    exeOrgIds = UserManager.getUsers().get(position).getBmcode();
                }
            });
        } else {
            requestData();
            tvSubmit.setVisibility(View.GONE);
            tvTitle.setEnabled(false);
            tvContent.setEnabled(false);
        }

    }


    private void requestData() {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.TASK_ENTITY);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                data = GsonUtil.GsonToBean(response, OtherOfficeDetailBean.class);
                tvTitle.setText(data.getTitle());
                tvRegister.setText(data.getReportor());
                tvRegisterOrg.setText(data.getOrgName());
                tvRegisterTime.setText(data.getReportDate());
                switch (data.getUrgent()) {
                    case "紧急":
                        rbHurrey.setChecked(true);
                        break;
                    case "普通":
                        rbNor.setChecked(true);
                        break;
                    case "催办":
                        rbErgent.setChecked(true);
                        break;
                }
                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(MissionActivity.this);

                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
//                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });
                spOpter.setText(data.getExeUserNames());
                tvContent.setText(data.getContext());
                spLeader1.setText(data.getDirector());
                spLeader2.setText(data.getResponsible());
                spOrg.setText(data.getOrgName());

                tvTime.setText(data.getTerm());
                if (data.getTaskType().equals("0")) {
                    linOrg.setVisibility(View.VISIBLE);
                    linPerson.setVisibility(View.GONE);
                    rbOrg.setChecked(true);
                } else {
                    linOrg.setVisibility(View.GONE);
                    linPerson.setVisibility(View.VISIBLE);
                    rbPerson.setChecked(true);
                }

            }
        });
    }

    @Override
    public void setListener() {

    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @OnClick({R.id.tv_register_time, R.id.rb_org, R.id.rb_person, R.id.rb_nor, R.id.rb_hurrey, R.id.rb_ergent, R.id.tv_time, R.id.tv_submit})
    public void onViewClicked(View view) {
        if (TextUtils.isEmpty(id)) {
            switch (view.getId()) {
                case R.id.tv_register_time:
                    TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            tvRegisterTime.setText(DateUtil.convert2String(date, format1));
                        }
                    }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                    pvTime.show();
                    break;
                case R.id.rb_org:
                    taskType = "0";
                    linOrg.setVisibility(View.VISIBLE);
                    linPerson.setVisibility(View.GONE);
                    break;
                case R.id.rb_person:
                    taskType = "1";
                    linOrg.setVisibility(View.GONE);
                    linPerson.setVisibility(View.VISIBLE);
                    break;
                case R.id.rb_nor:
                    urgent = "普通";
                    break;
                case R.id.rb_hurrey:
                    urgent = "紧急";
                    break;
                case R.id.rb_ergent:
                    urgent = "催办";
                    break;
                case R.id.tv_time:
                    TimePickerView pvTime2 = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            tvRegisterTime.setText(DateUtil.convert2String(date, format1));
                        }
                    }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                    pvTime2.show();
                    break;
                case R.id.tv_submit:
                    submit();
                    break;
            }
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            for (int i = 0; i < images.size(); i++) {
                                images.get(i).mimeType = "image";
                            }
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case RESULT_OK:
                    //选择视频返回
                    if (requestCode == REQUEST_CODE_VSELECT) {
                        List<String> videoUrls = Matisse.obtainPathResult(data);
                        Log.e("videoUrls", videoUrls.get(0));
                        videoPath = videoUrls.get(0);
                        MediaMetadataRetriever retr = new MediaMetadataRetriever();
                        retr.setDataSource(videoPath);
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = retr.getFrameAtTime();
                        String imgUrl = FileUtil.saveImg2Gallery(this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = imgUrl;
                        imageItem.name = videoPath;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        adapter.setImages(selImageList);

                    }
                    break;
            }
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                names.add("视频");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(MissionActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(MissionActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            case 2:
                                if (!(checkPermission(Manifest.permission.CAMERA))) {
                                    ActivityCompat.requestPermissions(MissionActivity.this, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                                } else {
                                    Matisse.from(MissionActivity.this)
                                            .choose(MimeType.ofVideo())
                                            .showSingleMediaType(true)
                                            .theme(R.style.Matisse_Dracula)
                                            .countable(false)
                                            .maxSelectable(1)
                                            .imageEngine(new GlideEngine())
                                            .forResult(REQUEST_CODE_VSELECT);
                                }

                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                if (adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }
                break;
        }
    }

    List<UpImgInfoBean> upImgInfoBeanList;

    private void submit() {
        if (TextUtils.isEmpty(tvTitle.getText().toString()) || TextUtils.isEmpty(tvContent.getText().toString())) {
            ToastUtils.showToast("请完善填写信息");
            return;
        }
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.USERTASKUPLOADDATA);

        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();
        HashMap<String, Object> map1 = new HashMap<>();

        map1.put("id", patrol.mobile.com.mobilepatrol.manager.UserManager.getUserId() + System.currentTimeMillis());
        map1.put("context", tvContent.getText().toString());
        map1.put("title", tvTitle.getText().toString());
//        map1.put("reportDate", tvRegisterTime.getText().toString());

        map1.put("reportDate", TimeUtils.timeToData(tvRegisterTime.getText().toString()));
        map1.put("exeUserNames", spOpter.getmText().getText().toString());
        map1.put("reportor", tvRegister.getText().toString());
        map1.put("orgName", tvRegisterOrg.getText().toString());
        map1.put("orgId", UserManager.getUser().getBmcode());
        HashMap<String, String> hashMap1 = new HashMap<>();
        hashMap1.put("id", UserManager.getUser().getBmcode());
        hashMap1.put("orgName", tvRegisterOrg.getText().toString());
        map1.put("org", hashMap1);
        map1.put("exeOrgIds", exeOrgIds);
        map1.put("exeUserIds", exeUserIds);
        map1.put("exeOrgNames", spOrg.getmText().getText().toString());
        map1.put("director", spOpter.getmText().getText().toString());
        map1.put("directorId", directorId);
        map1.put("responsible", spLeader2.getmText().getText().toString());
        map1.put("responsibleId", responsibleId);
        map1.put("urgent", urgent);
        map1.put("term", TimeUtils.timeToData(tvTime.getText().toString()));
        map1.put("taskType", taskType);
        map1.putAll(idDateBmnameMap);
        HashMap<String, String> map2 = new HashMap<>();
        map2.put("mainJson", GsonUtil.map2Json(map1));

        List<ImageItem> images = adapter.getImages();
        upImgInfoBeanList = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("abkDuty");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        // oldImgInfo.addAll(upImgInfoBeanList);
        map2.put("sysAttachmentsJson", GsonUtil.bean2Json(upImgInfoBeanList));
        sender.requestPost(map2, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    int state = jsonObject.getInt("state");
                    if (200 == state) {
                        sender.dismissDialog();
                        upImg();
                    } else {
                        Toast.makeText(MissionActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<Map<String, String>> params = new ArrayList<>();
            List<Map<String, String>> picparams = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "abkDuty");
                params.add(map);
            }
            for (int i = 0; i < selImageList.size(); i++) {
                File file;
                File videofile;
                if (selImageList.get(i).mimeType.equals("image")) {
                    file = new File(selImageList.get(i).path);
                    list.add(file);
                    picparams.add(params.get(i));
                } else {
                    videofile = new File(selImageList.get(i).name);
                    HttpSender sender = new HttpSender(this, baseUrl, Urls.IMG_UP_LOAD);
                    Map<String, String> map = new HashMap<>();
                    map.put("id", imgUUIDs.get(i));
                    map.put("type", "abkDuty");
                    int finalI = i;
                    sender.upImgs2(videofile, map, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Toast.makeText(MissionActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                            if (finalI == selImageList.size() - 1) {
                                finish();
                            }
                        }
                    });
                }
            }

            LuBanHelper luBanHelper = new LuBanHelper(MissionActivity.this, list, picparams);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(MissionActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

}
